import HeaderTab from "@/components/CommonTab/index";
import React, { useState, useEffect, useRef, useCallback } from "react";
import { message, Button, Statistic, Skeleton } from "antd";
import { SearchCheckboxTable } from "@/views/components/SearchTable/index";
import { LeftBtns, RightBtns } from "./components/TableHeader";
import { useTableConfig } from "@/views/components/SearchTable/hooks/useTableConfig";
import getColumns from "./cloumns";
import {
	getSuggestionPage,
	inventoryWarehouseList,
	queryAreaCode,
	getZJFStorePage,
	createPurchaseOrder,
	getAreaInfo
} from "./service";
import Actions, { DialogEnum } from "./components/Actions";
import Style from "./index.module.less";
import { uniqueId } from "lodash";
const defaultTabArr = () => {
	return [
		{
			tab: "已售采购建议",
			key: "0"
		},
		{
			tab: "库存采购建议",
			key: "1"
		}
	];
};
const defaultTotalData = () => {
	return {
		productTypesNum: 0,
		suppliersNum: 0,
		suggestNum: 0,
		actualNum: 0,
		price: "0.00"
	};
};
const defaultType = "0";
const rowKey = "uuid";
const defaultTabsValue = "近7天";

const TablePage = () => {
	// tabs 选项卡
	const [tabArr, setTabArr] = useState(defaultTabArr);
	const [type, setType] = useState(defaultType);
	const RefType = useRef(defaultType);
	// 仓库列表
	const warehouseList = useRef();
	// 供应商列表
	const supplierList = useRef();
	// 区域编码下拉项
	const areaOption = useRef();
	// 前端新增商品的数据
	const [addList, setAddList] = useState([]);
	// const [row, setRow] = useState({});
	const [totalData, setTotalData] = useState(defaultTotalData());
	const [totalLoading, setTotalLoading] = useState(false);
	const [codes, setCodes] = useState([]);
	// 打开弹窗名称
	const [actionName, setActionName] = useState(false);
	// 弹窗参数
	const [actionsProps, setActionsProps] = useState({});
	const tabsValue = useRef(defaultTabsValue);
	const { columns, setColumns, defaultColumns } = getColumns({
		supplierList,
		areaOption,
		handleChange,
		handleSearchForm,
		tabsValue
	});
	// 接口
	const tableRequest = getSuggestionPage;
	// const [columns, setColumns] = useState(defaultColumns);
	/**
	 * query              搜索json
	 * updateQuery        更新搜索json
	 * fetchList          刷新列表
	 * checkedIds         选中的行id数组
	 * checkedRows        选中的行数据
	 * CheckBoxTable      checkbox多选表格
	 * RadioTable         单选表格
	 */
	const beforeReset = useCallback(() => {
		tabsValue.current = defaultTabsValue;
	}, []);
	const tableKey = "StockManagePropose";
	const {
		RefTable,
		selectedKeys,
		selectedRows,
		fetchList,
		dataSource,
		form,
		query,
		pagination,
		updateDataSource,
		clearTableSelected,
		updateSearchQuery,
		updatePaginationParams,
		searchSimpleTableProps
	} = useTableConfig({
		tableKey,
		rowKey,
		// ///
		columns,
		tableRequest,
		autoFetch: false,
		hasPagination: true,
		hasQuickSearch: true,
		beforeReset,
		beforeQuerySearch,
		resetSourceData,
		hasColsSetting: true,
		hasToggleSearchForm: true,
		columnResize: true
		// sortProps
	});

	async function beforeQuerySearch({ API_DATA }) {
		await getSupplierData();
		getWarehouseColumns();
		getQueryAreaCode();
		return {
			...API_DATA,
			areaCodes: API_DATA?.areaCodes?.join(),
			type: RefType.current
		};
	}
	function resetSourceData(d) {
		const list = d.map(item => {
			return {
				...item,
				actualNum: item.suggestNum || item.actualNum,
				uuid: uniqueId()
			};
		});
		return list;
	}
	// 获取仓库列字段
	async function getWarehouseColumns() {
		const res = await inventoryWarehouseList();
		const { success, data } = res;
		if (success) {
			const list = [];
			data.forEach(item => {
				list.push({
					name: item.warehouseName,
					code: item.id,
					render: (v, record) => <>{record.warehouseMap[item.id].saleableNum}</>
				});
			});
			warehouseList.current = data;
			// setWarehouseList(data);
			setColumns([...defaultColumns, ...list]);
		}
	}
	// 获取供应商数据
	async function getSupplierData() {
		const res = await getZJFStorePage({ pageSize: 9999, size: 9999 });
		const { success, data } = res;
		if (success) {
			supplierList.current = data.records.map(e => {
				return {
					...e,
					value: e.storeId,
					label: e.storeName
				};
			});
		}
	}
	// 获取所属区域编码
	async function getArea(data) {
		const res = await getAreaInfo(data);
		// console.log(res.data[0]);
		return res.success ? res.data[0] : {};
	}
	// 修改搜索数据
	function handleSearchForm(data) {
		form.setFieldsValue({
			...data
		});
	}
	/**
	 * 处理数据源变更的函数。
	 * @param {Object} data - 要更新到表格中的数据对象。
	 * @param {number} index - 数据对象在数据源列表中的索引。
	 * @param {boolean} isTotal - 标识是否是总计行。当前未使用，但可能用于未来扩展。
	 */
	async function handleChange(data, index, isTotal) {
		// 清除表格中当前选定的行
		// clearTableSelected();

		// 判断是否是修改供应商，需要调用接口获取对应区域编码
		let areaData = {};
		const isSupplier = data.hasOwnProperty("supplierId");
		if (isSupplier) {
			areaData = await getArea({ supplierIds: [data.supplierId] });
			console.log("areaData", areaData);
		}

		let id = null;
		// 更新数据源，并在更新后执行额外操作
		updateDataSource(list => {
			id = list[index][rowKey]; // 获取即将更新行的ID
			// 遍历data对象的属性，并将其更新到列表的指定行
			Object.keys(data).forEach(key => {
				list[index][key] = data[key];
				if (isSupplier) {
					list[index]["areaName"] = areaData?.shopAreaName;
					list[index]["areaCode"] = areaData?.shopArea;
				}
			});
			// 如果更新的数据包含实际数量字段，执行特定逻辑
			if (isTotal) {
				// 使用setTimeout异步执行，以确保updateDataSource更新完成后再进行选中状态的设置
				const ids = new Set([...RefTable?.current?.getSelectedRowKeys(), id]);
				setTimeout(() => {
					RefTable?.current?.setTableSelect?.([...ids]);
					// 此处原计划执行getSummary函数，但当前注释掉了
				}, 100);
			}
			return list; // 返回更新后的数据列表
		});
	}

	// 获取区域编码
	async function getQueryAreaCode() {
		const { success, data } = await queryAreaCode({ areaCode: "" });
		if (success) {
			areaOption.current = data.map(e => {
				return {
					...e,
					value: e.id,
					label: e.name
				};
			});
		}
	}

	// 一键生成采购单
	const GeneratePurchaseOrder = async () => {
		// console.log("selectedRows", selectedRows);
		const rows = selectedRows.filter(e => e.supplierId && e.actualNum);
		if (rows.length === 0) return message.warning("没有可操作的数据，请重新勾选");
		// 重组数据
		// console.log("rows", rows);
		// 获取取供应商的ids集合
		const supplierIds = new Set(rows.map(e => e.supplierId));
		const API_LIST = [];
		// 获取相同供应商的商品
		supplierIds.forEach(supplierId => {
			// console.log("supplierId", supplierId);
			let childList = rows.filter(e => e.supplierId === supplierId);
			const data = {
				areaCode: childList[0].areaCode || null,
				areaName: childList[0].areaName || null,
				supplierId: childList[0].supplierId || null,
				supplierName: childList[0].supplierName || null,
				pickerId: childList[0].pickerId || null,
				pickerName: childList[0].pickerName || null,
				type,
				purchaseOrderDetailsDTOList: null
			};
			API_LIST.push(data);
			// sku 去重并累加【实际采购数】
			childList = childList.reduce((acc, current) => {
				const index = acc.findIndex(item => item.skuId === current.skuId);
				if (index != -1) {
					// 累加【实际采购数】
					acc[index].actualNum += current.actualNum;
				} else {
					acc.push(current);
				}
				return acc;
			}, []);
			// 采购详情表：同一个供应商的商品数据
			childList = childList.map(e => {
				return {
					skuId: e.skuId,
					skuName: e.skuName,
					skuImage: e.skuImage,
					// 商品简称
					skuAbbreviation: e.skuAbbreviation,
					skuSpec: e.skuSpec,
					skuCode: e.skuCode,
					// 供应商相关
					supplierSkuId: e.supplierSkuId || null,
					// supplierSkuCode: 就是supplierSkuId
					supplierSkuCode: e.supplierSkuId || null,
					supplierSkuName: e.supplierSkuName || null,
					supplierSkuImage: e.supplierSkuImage || null,
					supplierSkuSpec: e.supplierSkuSpecs || null,
					supplierSkuAbbreviation: e.supplierSkuAbbreviation || null,

					supplierSpuCode: e.supplierSpuCode || null,

					supplierId: e.supplierId || null,
					supplierName: e.supplierName || null,

					totalNum: e.actualNum
				};
			});
			data.purchaseOrderDetailsDTOList = childList;
		});
		// console.log(API_LIST);
		const res = await createPurchaseOrder(API_LIST);
		const { success, data } = res;
		if (success) {
			setCodes(data);
			setActionsProps({
				codes: data
			});
			setActionName(DialogEnum.CreatSuccess);
		}
	};

	// 计算汇总数据
	function getSummary() {
		setTotalLoading(true);
		// console.log("selectedRows", selectedRows);
		const rows = selectedRows.filter(e => e.supplierId && e.actualNum);
		// console.log("rows", rows);
		if (rows.length) {
			// console.log("多选", rows);
			let suggestNum = 0,
				actualNum = 0,
				price = 0;
			rows.forEach(item => {
				suggestNum = suggestNum + (item.suggestNum || 0);
				actualNum += Number(item.actualNum || 0);
				price = price + (item.skuPrice || 0) * (item.actualNum || 0);
			});
			setTotalData({
				productTypesNum: new Set(rows.map(e => e.skuCode)).size,
				suppliersNum: new Set(rows.map(e => e.supplierName)).size,
				suggestNum,
				actualNum,
				price
			});
		} else {
			setTotalData(defaultTotalData());
		}
	}

	const onCancel = () => {
		setActionName(false);
		setActionsProps({});
		clearTableSelected();
	};

	// 新增商品
	useEffect(() => {
		const fetchData = async () => {
			// console.log("addList", addList);
			let list = addList.map(item => {
				// console.log(item, "item");
				const data = item?.goodsSkuMatches.find(x => x.isDefault === 1);
				const firstData = item?.goodsSkuMatches.find((x, index) => index === 0);
				console.log(data, "data");
				return {
					...item,
					supplierId: data ? data.supplierId : firstData.supplierId,
					supplierName: data ? data.supplierName : firstData.supplierName,
					supplierSpuCode: data ? data.supplierSpuCode : firstData.supplierSpuCode,
					actualNum: item.actualNum ? item.actualNum : 1,
					uuid: uniqueId()
				};
			});
			// 需要去获取所属区域
			console.log("list", list);
			if (list.length) {
				const res = await getAreaInfo({ supplierIds: list.map(e => e.supplierId) });
				if (res.success) {
					// console.log(res.data);
					list = list.map(item => {
						const obj = res.data.find(e => item.supplierId == e.storeId) || {};
						// console.log("obj", obj);
						return {
							...item,
							areaCode: obj?.shopArea,
							areaName: obj?.shopAreaName
						};
					});
					// console.log("list", list);
					updateDataSource(v => {
						return [...list, ...v];
					});
				}
			}
		};
		fetchData();
	}, [addList]);
	// 当前tab
	const HeaderTabProps = {
		type,
		data: tabArr,
		// tabs 状态变更
		onChange(val) {
			// console.log(val);
			setType(val);
			// fetchList({ type: val });
		}
	};
	const tableHeaderProps = {
		type,
		setActionName,
		setActionsProps,

		addList,
		setAddList,
		warehouseList,
		selectedRows,
		dataSource,
		updateDataSource,
		searchForm: form,
		pagination,
		fetchList,
		onCancel
	};
	// 监听tabs切换
	useEffect(() => {
		const formData = form.getFieldsValue();
		RefType.current = type;
		fetchList({ type, ...formData }, { pageNum: 1 });
	}, [type]);
	// 多选监听操作
	useEffect(() => {
		getSummary();
		setTimeout(() => {
			setTotalLoading(false);
		}, 500);
	}, [selectedKeys]);
	//总计
	const Footer = () => {
		return (
			<div className="flx-justify-between" style={{ height: 41 }}>
				<span>总计</span>
				<div className={Style.total}>
					<Statistic
						prefix="商品种类："
						value={totalData.productTypesNum}
						precision={0}
						groupSeparator=""
						valueStyle={{ fontSize: 14, marginRight: 40, lineHeight: "21px" }}
					/>
					<Statistic
						prefix="供应商数："
						value={totalData.suppliersNum}
						precision={0}
						groupSeparator=""
						valueStyle={{ fontSize: 14, marginRight: 40, lineHeight: "21px" }}
					/>
					<Statistic
						prefix="原建议采购数："
						value={totalData.suggestNum}
						precision={0}
						groupSeparator=""
						valueStyle={{ fontSize: 14, marginRight: 40, lineHeight: "21px" }}
					/>
					<Statistic
						prefix="实际采购数："
						value={totalData.actualNum}
						precision={0}
						groupSeparator=""
						valueStyle={{ fontSize: 14, marginRight: 40, lineHeight: "21px" }}
					/>
					<Statistic
						prefix={<span style={{ color: "#333" }}>预计采购金额：￥</span>}
						value={totalData.price}
						precision={2}
						groupSeparator=""
						valueStyle={{ fontSize: 14, color: "#FF3838", marginRight: 40, lineHeight: "21px" }}
					/>
					<Button
						type="primary"
						onClick={GeneratePurchaseOrder}
						style={{ height: 32, width: 100, fontSize: 12, lineHeight: "18px" }}
					>
						一键生成采购单
					</Button>
				</div>
			</div>
		);
	};

	return (
		<>
			<SearchCheckboxTable
				key={tableKey}
				header={<HeaderTab {...HeaderTabProps} />}
				leftBtns={<LeftBtns {...tableHeaderProps} />}
				rightBtns={<RightBtns {...tableHeaderProps} />}
				tableFooter={<Footer />}
				{...searchSimpleTableProps}
			/>
			<Actions
				actionName={actionName}
				setActionName={setActionName}
				tabArr={defaultTabArr().map(e => {
					return { ...e, tab: e.tab + "规则" };
				})}
				onCancel={onCancel}
				{...actionsProps}
			/>
		</>
	);
};
export default React.memo(TablePage, () => {
	return true;
});
